package com.yoona.log.configure;



import com.yoona.common.utils.HttpServletRequestUtil;
import com.yoona.common.utils.IpUtil;
import com.yoona.log.entity.SysLogs;
import com.yoona.log.mapper.SysLogsMapper;
import com.yoona.log.persistence.MyLog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Email: m15602498163@163.com
 * @Author: yoonada
 * @Date: 2020/7/31
 * @Time: 11:02 上午
 * @Msg:
 */
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysLogsAspect {

    private final SysLogsMapper sysLogsMapper;

    /**
     * 定义切点 @Pointcut
     * 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.yoona.log.persistence.MyLog)")
    public void logPointCut() {
    }

    /**
     * 切面 配置通知
     * @param joinPoint
     */
    @AfterReturning(value = "logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        //保存日志
        SysLogs sysLogs = new SysLogs();
        HttpServletRequest request = HttpServletRequestUtil.getHttpServletRequest();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            String value = myLog.value();
            // 保存获取的操作
            sysLogs.setOperation(value);
        }
        String uid = (String) request.getAttribute("uid");
        String nickName = (String) request.getAttribute("nick_name");
        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //请求方式
        String requestMode = request.getMethod();
        //获取请求的方法名
        String methodName = method.getName();
        String url = request.getRequestURL().toString();
        String ipAddress = IpUtil.getClient(request);
        sysLogs.setMethod(className + "." + methodName);
        sysLogs.setUserName(nickName);
        sysLogs.setUid(uid);
        sysLogs.setCreateTime(new Date());
        sysLogs.setIp(ipAddress);
        sysLogs.setUrl(url);
        sysLogs.setRequestMode(requestMode);
        sysLogsMapper.insert(sysLogs);

    }



}
